package com.huicharge.huichargecrm.rpc;

import com.ludaniu.common.Invocation;
import com.ludaniu.common.NettyHeader;
import io.netty.buffer.ByteBuf;
import com.ludaniu.common.Packmsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

/**
 * @author 鲁昊天
 * @date 2025/4/30
 */
public class ServerDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buf, List<Object> list) throws Exception {
       while (buf.readableBytes()>=100){
           /*
           * 读取请求头
           * */
           byte[] bytes=new byte[100];
           buf.getBytes(buf.readerIndex(),bytes);
           ByteArrayInputStream bis=new ByteArrayInputStream(bytes);
           ObjectInputStream ois=new ObjectInputStream(bis);
           NettyHeader header=(NettyHeader)ois.readObject();
           //判断发送的是否是net-daniu的通信协议
           if(header.getFlag()!=0X14141414){
               throw new Exception("不符合net-daniu的通信协议");
           }
           System.out.println("[server 解码器]读取到请求头，id："+header.getRequestID());
           if(buf.readableBytes()>=header.getDataLen()){
               //处理指针
               buf.readBytes(100);
               //读取请求体
               byte[] data=new byte[(int)header.getDataLen()];
               buf.readBytes(data);
               bis=new ByteArrayInputStream(data);
               ois=new ObjectInputStream(bis);
               Invocation invocation =(Invocation)ois.readObject();
               list.add(new Packmsg(header,invocation));
           }else{
               System.out.println("[解码器]数据不够,等下次读取");
               break;
           }
       }
    }
}
